import {lazyReportCache} from "../utils/report.js";

// 将原始的fetch保存
const originalFetch = window.fetch
/**
 * 网络请求的监控（基于XMLHttpRequest封装的请求插件）
 * */
function overwrite() {
    window.fetch = function (url, config) {
        const startTime = Date.now()
        const reportData = {
            type: 'performance',
            subType: 'fetch',
            url,
            startTime,
            method: (config?.method || 'GET').toUpperCase(),
        }

        return originalFetch(url, config).then(res => {
            reportData.endTime = Date.now()
            reportData.duration = reportData.endTime - reportData.startTime

            const data = res.clone()
            reportData.status = data.status
            reportData.success = data.ok
            
            lazyReportCache(reportData)
            return res
        }).catch(err => {
            reportData.endTime = Date.now()
            reportData.duration = reportData.endTime - reportData.startTime
            reportData.status = 0
            reportData.success = false
            
            lazyReportCache(reportData)
            throw err
        })
    }
}

export default function observeFetch() {
    overwrite()
}
